// pages/calendar/calendar.js
const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentDate: new Date(),
    currentYear: 0,
    currentMonth: 0,
    calendarDays: [],
    menstrualData: {},
    selectedDate: null,
    showDateDetail: false,
    dateDetailInfo: {},
    showAddRecord: false,
    recordForm: {
      date: '',
      flowLevel: 1,
      symptoms: [],
      notes: ''
    },
    flowLevels: [
      { value: 1, name: '轻量', color: '#FFB6C1' },
      { value: 2, name: '中量', color: '#FF69B4' },
      { value: 3, name: '大量', color: '#DC143C' },
      { value: 4, name: '极大量', color: '#8B0000' }
    ],
    symptomOptions: [
      '腹痛', '腰痛', '头痛', '乳房胀痛', '情绪波动', 
      '疲劳', '恶心', '便秘', '腹泻', '失眠'
    ],
    statistics: {
      avgCycleLength: 0,
      avgPeriodLength: 0,
      nextPredictedDate: null,
      ovulationDate: null
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initCalendar();
    this.loadMenstrualData();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadMenstrualData();
  },

  /**
   * 初始化日历
   */
  initCalendar() {
    const now = new Date();
    this.setData({
      currentYear: now.getFullYear(),
      currentMonth: now.getMonth() + 1
    });
    this.generateCalendar();
  },

  /**
   * 生成日历数据
   */
  generateCalendar() {
    const { currentYear, currentMonth } = this.data;
    const firstDay = new Date(currentYear, currentMonth - 1, 1);
    const lastDay = new Date(currentYear, currentMonth, 0);
    const daysInMonth = lastDay.getDate();
    const startWeekDay = firstDay.getDay();
    
    const calendarDays = [];
    
    // 添加上个月的日期
    const prevMonth = currentMonth === 1 ? 12 : currentMonth - 1;
    const prevYear = currentMonth === 1 ? currentYear - 1 : currentYear;
    const prevMonthLastDay = new Date(prevYear, prevMonth, 0).getDate();
    
    for (let i = startWeekDay - 1; i >= 0; i--) {
      calendarDays.push({
        date: prevMonthLastDay - i,
        isCurrentMonth: false,
        fullDate: `${prevYear}-${String(prevMonth).padStart(2, '0')}-${String(prevMonthLastDay - i).padStart(2, '0')}`
      });
    }
    
    // 添加当前月的日期
    for (let date = 1; date <= daysInMonth; date++) {
      const fullDate = `${currentYear}-${String(currentMonth).padStart(2, '0')}-${String(date).padStart(2, '0')}`;
      calendarDays.push({
        date,
        isCurrentMonth: true,
        fullDate,
        isToday: this.isToday(currentYear, currentMonth, date)
      });
    }
    
    // 添加下个月的日期
    const nextMonth = currentMonth === 12 ? 1 : currentMonth + 1;
    const nextYear = currentMonth === 12 ? currentYear + 1 : currentYear;
    const remainingDays = 42 - calendarDays.length;
    
    for (let date = 1; date <= remainingDays; date++) {
      calendarDays.push({
        date,
        isCurrentMonth: false,
        fullDate: `${nextYear}-${String(nextMonth).padStart(2, '0')}-${String(date).padStart(2, '0')}`
      });
    }
    
    // 将一维数组转换为二维数组（6行7列）
    const calendarRows = [];
    for (let i = 0; i < 6; i++) {
      const row = calendarDays.slice(i * 7, (i + 1) * 7);
      if (row.length > 0) {
        calendarRows.push(row);
      }
    }
    
    this.setData({ 
      calendarDays: calendarRows
    });
  },

  /**
   * 判断是否为今天
   */
  isToday(year, month, date) {
    const today = new Date();
    return year === today.getFullYear() && 
           month === today.getMonth() + 1 && 
           date === today.getDate();
  },

  /**
   * 加载生理期数据
   */
  loadMenstrualData() {
    const { currentYear, currentMonth } = this.data;
    const startDate = `${currentYear}-${String(currentMonth).padStart(2, '0')}-01`;
    const endDate = `${currentYear}-${String(currentMonth).padStart(2, '0')}-31`;
    
    wx.request({
      url: `${app.globalData.baseUrl}/api/menstrual-cycles/calendar`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      data: {
        year: currentYear,
        month: currentMonth
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({
            menstrualData: res.data.data
          });
        }
      },
      fail: (err) => {
        console.error('加载生理期数据失败:', err);
      }
    });
    
    // 加载统计数据
    this.loadStatistics();
  },

  /**
   * 加载统计数据
   */
  loadStatistics() {
    wx.request({
      url: `${app.globalData.baseUrl}/api/menstrual-cycles/statistics`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({
            statistics: res.data.data
          });
        }
      }
    });
  },

  /**
   * 上一个月
   */
  prevMonth() {
    let { currentYear, currentMonth } = this.data;
    currentMonth--;
    if (currentMonth < 1) {
      currentMonth = 12;
      currentYear--;
    }
    this.setData({ currentYear, currentMonth });
    this.generateCalendar();
    this.loadMenstrualData();
  },

  /**
   * 下一个月
   */
  nextMonth() {
    let { currentYear, currentMonth } = this.data;
    currentMonth++;
    if (currentMonth > 12) {
      currentMonth = 1;
      currentYear++;
    }
    this.setData({ currentYear, currentMonth });
    this.generateCalendar();
    this.loadMenstrualData();
  },

  /**
   * 点击日期
   */
  onDateTap(e) {
    const { date, fullDate, isCurrentMonth } = e.currentTarget.dataset;
    if (!isCurrentMonth) return;
    
    this.setData({ selectedDate: fullDate });
    this.showDateDetail(fullDate);
  },

  /**
   * 显示日期详情
   */
  showDateDetail(date) {
    const { menstrualData } = this.data;
    const dateInfo = menstrualData[date] || {};
    
    this.setData({
      showDateDetail: true,
      dateDetailInfo: {
        date,
        ...dateInfo
      }
    });
  },

  /**
   * 关闭日期详情
   */
  closeDateDetail() {
    this.setData({ showDateDetail: false });
  },

  /**
   * 显示添加记录弹窗
   */
  showAddRecord() {
    const { selectedDate } = this.data;
    this.setData({
      showAddRecord: true,
      'recordForm.date': selectedDate,
      showDateDetail: false
    });
  },

  /**
   * 关闭添加记录弹窗
   */
  closeAddRecord() {
    this.setData({ 
      showAddRecord: false,
      recordForm: {
        date: '',
        flowLevel: 1,
        symptoms: [],
        notes: ''
      }
    });
  },

  /**
   * 选择流量等级
   */
  selectFlowLevel(e) {
    const level = e.currentTarget.dataset.level;
    this.setData({
      'recordForm.flowLevel': level
    });
  },

  /**
   * 选择症状
   */
  toggleSymptom(e) {
    const symptom = e.currentTarget.dataset.symptom;
    const { symptoms } = this.data.recordForm;
    const index = symptoms.indexOf(symptom);
    
    if (index > -1) {
      symptoms.splice(index, 1);
    } else {
      symptoms.push(symptom);
    }
    
    this.setData({
      'recordForm.symptoms': symptoms
    });
  },

  /**
   * 输入备注
   */
  onNotesInput(e) {
    this.setData({
      'recordForm.notes': e.detail.value
    });
  },

  /**
   * 保存记录
   */
  saveRecord() {
    const { recordForm } = this.data;
    
    if (!recordForm.date) {
      wx.showToast({ title: '请选择日期', icon: 'none' });
      return;
    }
    
    wx.request({
      url: `${app.globalData.baseUrl}/menstrual-cycles`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
        'Content-Type': 'application/json'
      },
      data: {
        startDate: recordForm.date,
        endDate: recordForm.date,
        flowLevel: recordForm.flowLevel,
        symptoms: recordForm.symptoms.join(','),
        notes: recordForm.notes
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({ title: '保存成功' });
          this.closeAddRecord();
          this.loadMenstrualData();
        } else {
          wx.showToast({ title: res.data.message || '保存失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('保存记录失败:', err);
        wx.showToast({ title: '保存失败', icon: 'none' });
      }
    });
  },

  /**
   * 删除记录
   */
  deleteRecord() {
    const { dateDetailInfo } = this.data;
    
    if (!dateDetailInfo.id) {
      wx.showToast({ title: '没有可删除的记录', icon: 'none' });
      return;
    }
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条记录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.request({
            url: `${app.globalData.baseUrl}/menstrual-cycles/${dateDetailInfo.id}`,
            method: 'DELETE',
            header: {
              'Authorization': `Bearer ${wx.getStorageSync('token')}`
            },
            success: (res) => {
              if (res.data.code === 200) {
                wx.showToast({ title: '删除成功' });
                this.closeDateDetail();
                this.loadMenstrualData();
              } else {
                wx.showToast({ title: res.data.message || '删除失败', icon: 'none' });
              }
            },
            fail: (err) => {
              console.error('删除记录失败:', err);
              wx.showToast({ title: '删除失败', icon: 'none' });
            }
          });
        }
      }
    });
  },

  /**
   * 获取日期样式类
   */
  getDateClass(date, menstrualData) {
    const dateStr = date.fullDate;
    const data = menstrualData[dateStr];
    
    if (!data) return '';
    
    if (data.isPredicted) {
      return 'predicted-period';
    } else if (data.flowLevel) {
      return `period-level-${data.flowLevel}`;
    }
    
    return '';
  },

  /**
   * 更新生理期记录
   */
  updateRecord() {
    const { dateDetailInfo } = this.data;
    
    if (!dateDetailInfo.id) {
      wx.showToast({ title: '没有可更新的记录', icon: 'none' });
      return;
    }
    
    // 设置表单数据为当前记录的数据
    this.setData({
      showAddRecord: true,
      showDateDetail: false,
      'recordForm.date': dateDetailInfo.date,
      'recordForm.flowLevel': dateDetailInfo.flowLevel || 1,
      'recordForm.symptoms': dateDetailInfo.symptoms ? dateDetailInfo.symptoms.split(',') : [],
      'recordForm.notes': dateDetailInfo.notes || ''
    });
  },

  /**
   * 保存或更新记录
   */
  saveOrUpdateRecord() {
    const { recordForm, dateDetailInfo } = this.data;
    
    if (!recordForm.date) {
      wx.showToast({ title: '请选择日期', icon: 'none' });
      return;
    }
    
    const isUpdate = dateDetailInfo.id;
    const url = isUpdate 
      ? `${app.globalData.baseUrl}/menstrual-cycles/${dateDetailInfo.id}`
      : `${app.globalData.baseUrl}/menstrual-cycles`;
    const method = isUpdate ? 'PUT' : 'POST';
    
    wx.request({
      url,
      method,
      header: {
        'Authorization': `Bearer ${wx.getStorageSync('token')}`,
        'Content-Type': 'application/json'
      },
      data: {
        startDate: recordForm.date,
        endDate: recordForm.date,
        flowLevel: recordForm.flowLevel,
        symptoms: recordForm.symptoms.join(','),
        notes: recordForm.notes
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({ title: isUpdate ? '更新成功' : '保存成功' });
          this.closeAddRecord();
          this.loadMenstrualData();
        } else {
          wx.showToast({ title: res.data.message || '操作失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('保存记录失败:', err);
        wx.showToast({ title: '操作失败', icon: 'none' });
      }
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadMenstrualData();
    wx.stopPullDownRefresh();
  }
})